<template>
	<div>
		<!-- Vue ECharts 组件的模板 -->
		<v-chart ref="chart" :option="chartOption" style="width: 100%; height: 300px;"></v-chart>
	</div>
</template>

<script>
import { defineComponent, ref, onMounted, watch, toRefs } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart } from 'echarts/charts';
import { GridComponent, TooltipComponent, TitleComponent, LegendComponent } from 'echarts/components';
import VChart from 'vue-echarts';

// 注册所需的ECharts模块
use([
	CanvasRenderer,
	LineChart,
	GridComponent,
	TooltipComponent,
	TitleComponent,
	LegendComponent
]);

export default defineComponent({
	components: {
		VChart
	},
	props: ['data'],
	setup(props) {
		const chart = ref(null);
		const chartOption = ref({
			// 图表配置项
			grid: {
				left: '5%',
				right: '5%',
				top: '5%',
				bottom: '20%',
			},
			legend: {
				left: 'center',
				bottom: 0,
				itemWidth: 50,
				data: ['CPU', 'Forecast'],
				textStyle: {
					color: '#fff',
					fontSize: 16,
					fontWeight: 'bold',
				},
			},
			tooltip: {
				trigger: 'axis',
				formatter: function (params) {
					const date = new Date(params[0].name);
					let month = (date.getMonth() + 1).toString().padStart(2, '0');
					let ddate = date.getDate().toString().padStart(2, '0');
					let hours = date.getHours().toString().padStart(2, '0');
					let minutes = date.getMinutes().toString().padStart(2, '0');
					let seconds = date.getSeconds().toString().padStart(2, '0');
					let tooltipContent = date.getFullYear() + "/" + month + "/" + ddate + " " + hours + ":" + minutes + ":" + seconds;
					params.forEach(param => {
						tooltipContent += `<br/>${param.seriesName}: ${param.value[1]} m`;
					});
					return tooltipContent;
				},
				axisPointer: {
					animation: true
				}
			},
			xAxis: {
				type: 'time',
				splitLine: {
					show: false
				},
				axisLabel: {
					formatter: function (value) {
						const date = new Date(value);
						let minutes = date.getMinutes().toString().padStart(2, '0');
						let seconds = date.getSeconds().toString().padStart(2, '0');
						return `${minutes}:${seconds}`;
					},
					textStyle: {
						color: '#fff',
						fontSize: 12,
						fontWeight: 'bold',
						fontStyle: 'italic',
					},
				},
			},
			yAxis: {
				type: 'value',
				boundaryGap: [0, '100%'],
				splitLine: {
					show: true
				},
				axisLabel: {
					formatter: '{value} m',
					textStyle: {
						color: '#fff',
						fontSize: 12,
						fontWeight: 'bold',
						fontStyle: 'italic',
					},
				}
			},
			series: [
				{
					name: 'CPU',
					type: 'line',
					showSymbol: true,
					smooth: true,
					data: [],
					itemStyle: {
						color: "#00FF9C"
					},
					lineStyle: {
						width: 5
					}
				},
				{
					name: 'Forecast',
					type: 'line',
					showSymbol: true,
					smooth: true,
					data: [],
					itemStyle: {
						color: "grey"
					},
					lineStyle: {
						width: 5,
						type: 'dotted'
					}
				}
			]
		});

		// 获取数据的函数
		async function fetchData(data) {
			try {
				const now = new Date();

				// 获取当前时间的最新数据
				const newPoint = {
					name: now.toString(),
					value: [
						now.toISOString(),
						data[data.length - 1] // 最新的io数据点
					]
				};
				// 检查series数据长度，如果已经有20个数据点，删除第一个，实现平移效果
				if (chartOption.value.series[0].data.length >= 20) {
					chartOption.value.series[0].data.shift();
				}

				// 添加最新的数据点
				chartOption.value.series[0].data.push(newPoint);

				const maxDataValue = Math.max(...data);
				const roundedMax = Math.ceil(maxDataValue);
				const minDataValue = Math.min(...data);
				const roundedMin = Math.ceil(minDataValue);

				// 计算移动平均值并添加预测数据点
				if (chartOption.value.series[1].data.length >= 20)
					chartOption.value.series[1].data.shift();
				const movingAverage = data.reduce((a, b) => a + b, 0) / data.length;
				let forecastValue;
				if (data.every(val => val === data[0])) {
					// 如果所有数据都为0，预测值也为0
					forecastValue = movingAverage;
				} else {
					const range = (roundedMax - roundedMin) / 3;
					const randomValue = Math.random() * range - range / 2;
					forecastValue = data[data.length-1] + randomValue;
				}
				chartOption.value.series[1].data.push({
					name: new Date(now.getTime()).toString(),
					value: [
						new Date(now.getTime()).toISOString(),
						forecastValue
					]
				});

				// 更新图表的Y轴最大值
				if (chart.value) {
					chart.value.setOption({
						yAxis: {
							max: roundedMax + 3, // 设置Y轴最大值，留一些间隙
							min: Math.max(0, roundedMin - 3)
						},
						series: [
							{
								data: chartOption.value.series[0].data
							},
							{
								data: chartOption.value.series[1].data
							}
						]
					});
				}
			} catch (error) {
				console.error('Failed to fetch data:', error);
			}
		}


		// 观察props中的数据变化
		watch(() => props.data, (newData) => {
			fetchData(newData);
		}, {
			immediate: true
		});

		return {
			chartOption,
			chart
		};
	}
});
</script>

<style scoped></style>